package com.hcj.springcloud.thread;

/**
 * 死锁demo
 *
 * @author huangcj
 * @date 2021-04-26 10:37
 */
public class DeadLockThread {
    public static final Object objA = new Object();
    public static final Object objB = new Object();

    public static void deadLock() {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (objA) {
                    System.out.println(Thread.currentThread().getName() + "获取到--》" + "objA的锁");
                    // 休眠500毫秒
                    try {
                        Thread.sleep(500L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (objB) {
                        System.out.println(Thread.currentThread().getName() + "获取到--》" + "objB的锁");
                    }
                }

            }
        }, "线程A");

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (objB) {
                    System.out.println(Thread.currentThread().getName() + "获取到--》" + "objB的锁");
                    // 休眠500毫秒
                    try {
                        Thread.sleep(500L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (objA) {
                        System.out.println(Thread.currentThread().getName() + "获取到--》" + "objA的锁");
                    }
                }

            }
        }, "线程B");

        threadA.start();
        threadB.start();
    }

    public static void main(String[] args) {
        deadLock();
    }
}
